package com.carrental.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carrental.common.exception.BusinessException;
import com.carrental.crm.dto.FeedbackDTO;
import com.carrental.crm.entity.Feedback;
import com.carrental.crm.mapper.FeedbackMapper;
import com.carrental.crm.service.FeedbackService;
import com.carrental.crm.vo.FeedbackVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 反馈服务实现类
 */
@Service
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback> implements FeedbackService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createFeedback(FeedbackDTO feedbackDTO) {
        // 创建反馈实体
        Feedback feedback = new Feedback();
        BeanUtils.copyProperties(feedbackDTO, feedback);
        
        // 设置默认值
        if (feedback.getStatus() == null) {
            feedback.setStatus(1); // 默认待处理状态
        }
        
        feedback.setCreateTime(LocalDateTime.now());
        feedback.setUpdateTime(LocalDateTime.now());
        
        // 保存反馈信息
        save(feedback);
        return feedback.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateFeedback(FeedbackDTO feedbackDTO) {
        if (feedbackDTO.getId() == null) {
            throw new BusinessException("反馈ID不能为空");
        }
        
        Feedback feedback = getById(feedbackDTO.getId());
        if (feedback == null) {
            throw new BusinessException("反馈不存在");
        }
        
        BeanUtils.copyProperties(feedbackDTO, feedback);
        feedback.setUpdateTime(LocalDateTime.now());
        
        return updateById(feedback);
    }

    @Override
    public FeedbackVO getFeedbackById(Long id) {
        Feedback feedback = getById(id);
        if (feedback == null) {
            return null;
        }
        return convertToVO(feedback);
    }

    @Override
    public Page<FeedbackVO> getFeedbacksByOrderId(Long orderId, Page<Feedback> page) {
        if (orderId == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        LambdaQueryWrapper<Feedback> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Feedback::getOrderId, orderId)
                .orderByDesc(Feedback::getCreateTime);
        
        Page<Feedback> feedbackPage = page(page, queryWrapper);
        return convertToVOPage(feedbackPage);
    }

    @Override
    public Page<FeedbackVO> pageUserFeedbacks(Long userId, Page<Feedback> page) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        LambdaQueryWrapper<Feedback> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Feedback::getUserId, userId)
                .orderByDesc(Feedback::getCreateTime);
        
        Page<Feedback> feedbackPage = page(page, queryWrapper);
        return convertToVOPage(feedbackPage);
    }

    @Override
    public Page<FeedbackVO> pageFeedbacks(Page<Feedback> page, String title, Integer type, Integer status, Long userId, Long customerId, Long orderId, String startTime, String endTime) {
        LambdaQueryWrapper<Feedback> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (StringUtils.isNotBlank(title)) {
            queryWrapper.like(Feedback::getTitle, title);
        }
        if (type != null) {
            queryWrapper.eq(Feedback::getType, type);
        }
        if (status != null) {
            queryWrapper.eq(Feedback::getStatus, status);
        }
        if (userId != null) {
            queryWrapper.eq(Feedback::getUserId, userId);
        }
        if (customerId != null) {
            queryWrapper.eq(Feedback::getCustomerId, customerId);
        }
        if (orderId != null) {
            queryWrapper.eq(Feedback::getOrderId, orderId);
        }
        
        // 处理时间范围
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (StringUtils.isNotBlank(startTime)) {
            LocalDateTime startDateTime = LocalDateTime.parse(startTime, formatter);
            queryWrapper.ge(Feedback::getCreateTime, startDateTime);
        }
        if (StringUtils.isNotBlank(endTime)) {
            LocalDateTime endDateTime = LocalDateTime.parse(endTime, formatter);
            queryWrapper.le(Feedback::getCreateTime, endDateTime);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Feedback::getCreateTime);
        
        // 执行分页查询
        Page<Feedback> feedbackPage = page(page, queryWrapper);
        return convertToVOPage(feedbackPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handleFeedback(Long id, Long handlerId, String handlerName, String handleResult) {
        if (id == null || handlerId == null || StringUtils.isBlank(handlerName) || StringUtils.isBlank(handleResult)) {
            throw new BusinessException("参数不能为空");
        }
        
        Feedback feedback = getById(id);
        if (feedback == null) {
            throw new BusinessException("反馈不存在");
        }
        
        // 只有待处理和处理中的反馈可以处理
        if (feedback.getStatus() != 1 && feedback.getStatus() != 2) {
            throw new BusinessException("该反馈状态不允许处理");
        }
        
        feedback.setHandlerId(handlerId);
        feedback.setHandlerName(handlerName);
        feedback.setHandleResult(handleResult);
        feedback.setHandleTime(LocalDateTime.now());
        feedback.setStatus(3); // 已处理
        feedback.setUpdateTime(LocalDateTime.now());
        
        return updateById(feedback);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean evaluateFeedback(Long id, Integer satisfaction, String evaluation) {
        if (id == null || satisfaction == null) {
            throw new BusinessException("参数不能为空");
        }
        
        Feedback feedback = getById(id);
        if (feedback == null) {
            throw new BusinessException("反馈不存在");
        }
        
        // 只有已处理的反馈可以评价
        if (feedback.getStatus() != 3) {
            throw new BusinessException("该反馈状态不允许评价");
        }
        
        feedback.setSatisfaction(satisfaction);
        feedback.setEvaluation(evaluation);
        feedback.setStatus(4); // 已关闭
        feedback.setUpdateTime(LocalDateTime.now());
        
        return updateById(feedback);
    }

    /**
     * 将反馈实体转换为VO
     *
     * @param feedback 反馈实体
     * @return 反馈VO
     */
    private FeedbackVO convertToVO(Feedback feedback) {
        if (feedback == null) {
            return null;
        }
        
        FeedbackVO vo = new FeedbackVO();
        BeanUtils.copyProperties(feedback, vo);
        
        // 处理图片列表
        if (StringUtils.isNotBlank(feedback.getImages())) {
            vo.setImageList(feedback.getImages().split(","));
        }
        
        // 设置类型名称
        if (feedback.getType() != null) {
            switch (feedback.getType()) {
                case 1:
                    vo.setTypeName("投诉");
                    break;
                case 2:
                    vo.setTypeName("建议");
                    break;
                case 3:
                    vo.setTypeName("咨询");
                    break;
                case 4:
                    vo.setTypeName("表扬");
                    break;
                default:
                    vo.setTypeName("未知");
            }
        }
        
        // 设置状态名称
        if (feedback.getStatus() != null) {
            switch (feedback.getStatus()) {
                case 1:
                    vo.setStatusName("待处理");
                    break;
                case 2:
                    vo.setStatusName("处理中");
                    break;
                case 3:
                    vo.setStatusName("已处理");
                    break;
                case 4:
                    vo.setStatusName("已关闭");
                    break;
                default:
                    vo.setStatusName("未知");
            }
        }
        
        return vo;
    }

    /**
     * 将反馈分页数据转换为VO分页
     *
     * @param page 反馈分页
     * @return 反馈VO分页
     */
    private Page<FeedbackVO> convertToVOPage(Page<Feedback> page) {
        Page<FeedbackVO> voPage = new Page<>();
        BeanUtils.copyProperties(page, voPage, "records");
        
        List<FeedbackVO> voList = new ArrayList<>();
        for (Feedback feedback : page.getRecords()) {
            voList.add(convertToVO(feedback));
        }
        voPage.setRecords(voList);
        
        return voPage;
    }
} 